package org.example.mybatisplus.controller;

import com.google.protobuf.ServiceException;
import org.example.mybatisplus.dao.entity.Student;
import org.example.mybatisplus.service.IStudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.util.List;
/**
 * 学生管理控制器 thymeleaf模板引擎实现页面跳转和数据处理
 */
@Controller
@RequestMapping("/studentpage")
public class StudentPageController {
    @Autowired
    private IStudentService studentService;

    /**
     * 查询学生列表信息
     * <p>

     * @return 学生信息
     */
    @GetMapping("/list")
    public String getStudentList(Model model, Student student) {
        List<Student> list =  studentService.list();
        model.addAttribute("list", list);
        return "student/list";
    }

    /**
     * 打开学生新增页面
     * <p>

     * @return 新增页面
     */
    @GetMapping("addpage")
    public String addpage(Model model, @ModelAttribute Student student, @RequestParam(value = "id",required = false) Integer id){
        if(id != null){
            Student byId = studentService.getById(id);
            model.addAttribute("student",byId);
        }
        return "student/add";
    }

    /**
     * 保存用户信息
     * <p>
     * 根据用户ID查询学生对象详细信息。
     *
     * @param student 学生对象
     * @return 学生对象
     */
    @PostMapping(value = {"/add", "/update"}, produces = "application/json")
    public String saveOrUpdate(Model model, Student student) {
        studentService.saveOrUpdate(student);
        return getStudentList(model,student);
    }


    /**
     * 删除学生信息
     * @param id
     * @return
     */
    @DeleteMapping("/delete")
    @ResponseBody
    public String deleteStudentById(Integer id) {
        studentService.removeById(id);
        return "success";
    }
}
